package fmt_m

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"os"
	"strings"
)

func FmtPbMessageMumber(params []string) error {
	if len(params) < 1 {
		return fmt.Errorf("No file path specified")
	}

	file_path := params[0]

	struct_name := ""
	if len(params) > 1 {
		struct_name = params[1]
	}

	f, err := os.Open("./" + file_path)
	if err != nil {
		return err
	}

	var fmted_buf bytes.Buffer

	unit, fmted, buf := (*MessageUnit)(nil), false, bufio.NewReader(f)
	for {
		line, err := buf.ReadString('\n')
		if err != nil {
			if err == io.EOF {
				line += "\n"
				fmted_buf.WriteString(line)
				break
			}
			return err
		}

		line_ := strings.TrimSpace(line)
		if strings.HasPrefix(line_, "message ") {
			unit = nil // 重置
			sname := strings.Split(strings.Fields(line_)[1], "{")[0]
			if struct_name == "" || struct_name == sname {
				unit = &MessageUnit{name: sname, adding: true}
				fmted_buf.WriteString(line)
				continue
			}
		}

		if unit != nil {
			switch {
			// 结束添加成员
			case unit.adding && strings.HasPrefix(line_, "}"):
				fmted = true
				unit.adding = false // 这个地方要处理增加修改量了
				fmted_buf.WriteString(unit.fmtstr())
				fmted_buf.WriteString(line)
				continue
			// 继续添加
			case unit.adding:
				if len(line_) > 0 {
					fields := strings.Fields(line_)
					commnt := ""
					if ss := strings.Split(line_, "//"); len(ss) > 1 {
						commnt = ss[1]
					}
					unit.addMember(fields[0], fields[1], strings.TrimSpace(commnt))
				}
				continue
			}
		}

		fmted_buf.WriteString(line)
	}
	f.Close()

	if !fmted {
		return fmt.Errorf("nothing")
	}
	// 写调整后的
	f, err = os.OpenFile("./"+file_path, os.O_RDWR|os.O_TRUNC, 0666)
	if err != nil {
		return err
	}
	fmted_buf.WriteTo(f)
	f.Close()

	return nil
}
